import os
from django.db.models import Max
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.views import View

from appAdminUserManagement.forms import SelectClassForm, SelectCollegeForm, SelectUsertypeForm, UploadFileForm
from djangoProject.settings import MEDIA_ROOT
from .models import User
from . import models
from django.core.exceptions import ObjectDoesNotExist
from django import forms
import pandas as pd


# form test
# def test_parent(request):
#     return render(request, 'tests/test_parent.html')
#
#
# def test_child(request):
#     name = 'xiaoming'
#     course = ['python', 'django', 'flask']
#     return render(request, 'tests/test_child.html', locals())


# class CollegeForm(forms.Form):
#     college_name = models.College.objects.values('college_name')
#     print(college_name)
#
#
# def test(request):
#     college_name = models.College.objects.values_list('college_name')
#     print(college_name)
#     college_list = []
#     for i in college_name:
#         for j in i:
#             college_list.append(j)
#     print(college_list)
#     res = []
#     for i in range(len(college_list)):
#         res.append((i + 1, college_list[i]))
#     res = tuple(res)
#     print(res)
#     # classId = forms.IntegerField(widget=forms.widgets.Select(choices=res))
#     return HttpResponse('test')


def accounts_upload(request):
    uploadedFile = request.FILES.get('file')
    filename = os.path.join(MEDIA_ROOT, uploadedFile.name).replace('\\', '/')

    saveFile(uploadedFile, filename)
    df = pd.read_excel(filename)
    print(type(df))
    rows, cols = df.shape
    print(rows)
    print(cols)
    for i in range(rows):
        models.User.objects.create(state=df.iloc[i, 0],
                                   name=df.iloc[i, 1],
                                   sid=df.iloc[i, 2],
                                   password=df.iloc[i, 3],
                                   college=df.iloc[i, 4],
                                   class_field=df.iloc[i, 5])
    msg = '用户添加成功，总计导入' + str(rows) + '个用户'
    return JsonResponse({'return_msg': msg})


# def excelUserInfo(request):
#     if request.method == 'GET':
#         return render(request, 'tests/file.html')
#
#     uploadedFile = request.FILES.get('file')
#     filename = os.path.join(MEDIA_ROOT, uploadedFile.name).replace('\\', '/')
#
#     saveFile(uploadedFile, filename)
#
#     df = pd.read_excel(filename)
#     print(type(df))
#     rows, cols = df.shape
#     print(rows)
#     print(cols)
#     for i in range(rows):
#         models.User.objects.create(state=df.iloc[i, 0],
#                                    name=df.iloc[i, 1],
#                                    sid=df.iloc[i, 2],
#                                    password=df.iloc[i, 3],
#                                    college=df.iloc[i, 4],
#                                    class_field=df.iloc[i, 5])
#     return HttpResponse('done')


def saveFile(received_file, filename):
    with open(filename, 'wb') as f:
        f.write(received_file.read())


# Create your views here.
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})


def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)


def upload(request):
    if request.method == 'GET':
        return render(request, 'tests/admin_userManagement_student.html')

    uploadedFile = request.FILES.get('file')
    filename = os.path.join(MEDIA_ROOT, uploadedFile.name).replace('\\', '/')

    saveFile(uploadedFile, filename)

    df = pd.read_excel(filename)
    print(type(df))
    rows, cols = df.shape
    print(rows)
    print(cols)
    for i in range(rows):
        models.User.objects.create(state=df.iloc[i, 0],
                                   name=df.iloc[i, 1],
                                   sid=df.iloc[i, 2],
                                   password=df.iloc[i, 3],
                                   college=df.iloc[i, 4],
                                   class_field=df.iloc[i, 5])
    return render(request, 'tests/admin_userManagement_student.html')
# 定义登录验证的装饰器

class indexView(View):

    def get(self, request):
        if request.session.get('name'):
            return render(request, 'admin_userManagement/admin_userManagement_index.html',
                          {'name': request.session.get('name'), 'state': request.session.get('state')})
        else:
            return redirect('/login/')


    def post(self, request):
        return render(request, 'admin_userManagement/admin_userManagement_index.html')


class studentView(View):
    userlist = User.objects.filter(state=2)

    def get(self, request):
        if request.session.get('name'):
            return render(request, 'admin_userManagement/admin_userManagement_student.html',
                          {'name': request.session.get('name'), 'userlist': self.userlist,
                           'state': request.session.get('state')})
        else:
            return redirect('/login/')

    def post(self, request):
        return render(request, 'admin_userManagement/admin_userManagement_student.html')


class teacherView(View):
    userlist = User.objects.filter(state=1)

    def get(self, request):
        if request.session.get('name'):
            return render(request, 'admin_userManagement/admin_userManagement_teacher.html',
                          {'name': request.session.get('name'), 'userlist': self.userlist,
                           'state': request.session.get('state')})
        else:
            return redirect('/login/')

    def post(self, request):
        return render(request, 'admin_userManagement/admin_userManagement_teacher.html')


class college_adminView(View):
    userlist = User.objects.filter(state=3)

    def get(self, request):
        if request.session.get('name'):
            return render(request, 'admin_userManagement/admin_userManagement_teacher.html',
                          {'name': request.session.get('name'), 'userlist': self.userlist,
                           'state': request.session.get('state')})
        else:
            return redirect('/login/')

    def post(self, request):
        return render(request, 'admin_userManagement/admin_userManagement_teacher.html')


class addView(View):
    def get(self, request):
        if request.session.get('name'):
            select_class = SelectClassForm()
            select_usertype = SelectUsertypeForm()
            select_college = SelectCollegeForm()
            return render(request, 'admin_userManagement/add.html', {'select_class': select_class, 'select_usertype': select_usertype,
                                            'select_college': select_college})
        else:
            return redirect('/login/')
    def post(self, request):
        sid = request.POST.get('sid')
        username = request.POST.get('name')
        pwd = request.POST.get('pwd')
        usertype = request.POST.get('state', 0)
        collegeId = request.POST.get('collegeId', 0)
        classId = request.POST.get('classId', 0)

        if usertype == 4:
            collegeId = 0
            classId = 0
        elif usertype == 3 or usertype == 2:
            classId = 0

        # 错误检测程序
        # 看看工号有没有已经注册过
        userlist = models.User.objects.filter(sid=sid)
        print(userlist)
        if not userlist.exists():
            # 可以注册
            models.User.objects.create(state=usertype,
                                       name=username,
                                       sid=sid,
                                       password=pwd,
                                       college=collegeId,
                                       class_field=classId)

            return redirect('/admin_userManagement')
        # 注册过，提示错误信息，并提供一个可用的号码

        max_uid_dict = models.User.objects.all().aggregate(max=Max('uid'))
        sid = '4192' + str(max_uid_dict['max'] + 1)
        error_msg = '工号已被使用，可以使用：' + str(sid)

        select_class = SelectClassForm()
        select_usertype = SelectUsertypeForm()
        select_college = SelectCollegeForm()
        return render(request, 'admin_userManagement/add.html', {'select_class': select_class, 'select_usertype': select_usertype,
                                        'select_college': select_college, 'error_msg': error_msg})


def add_success(request):
    if request.POST:
        if request.POST.get('jobnumber', -1) == -1:  # 没输入工号，让主键自增生成一个工号
            models.User.objects.create(name=request.POST.get('username', 'default_name'),
                                       password=request.POST.get('password', '123456'),
                                       state=request.POST.get('usertype', 3),
                                       class_field=request.POST.get('classId', 1))
        else:
            models.User.objects.create(sid=request.POST.get('jobnumber', 0),
                                       name=request.POST.get('username', 'default_name'),
                                       password=request.POST.get('password', '123456'),
                                       state=request.POST.get('usertype', 3),
                                       class_field=request.POST.get('classId', 1))

    return render(request, '')


def delete(request, sid):
    if request.session.get('name'):

        models.User.objects.filter(sid=sid).delete()
        return redirect('/admin_userManagement')
    else:
        return redirect('/login/')


def update(request, sid):
    if request.session.get('name'):

        models.User.objects.filter(sid=sid).update(password='123456')
        return redirect('/admin_userManagement')

    else:
        return redirect('/login/')




def myLogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    error_msg = ''
    sid = request.POST.get('sid', None)
    pwd = request.POST.get('password', None)
    print(sid)
    print(pwd)
    try:
        user = models.User.objects.get(sid=sid)
        if pwd != user.password:
            error_msg = '您输入的账户名或密码不正确'
        else:
            request.session['uid'] = user.uid
            request.session['state'] = user.state
            request.session['name'] = user.name
            request.session['sid'] = user.sid
            request.session['pwd'] = user.password
            request.session['college'] = user.college
            request.session['classId'] = user.class_field

            if user.state == 1:
                return redirect('/teareserve/')
            elif user.state == 2:
                return redirect('/stureserve/')
            elif user.state == 3:
                return redirect('/admin_userManagement/')
            elif user.state == 4:
                return redirect('/admin_userManagement/')
            else:
                error_msg = '用户类型未指定'
    except ObjectDoesNotExist:
        error_msg = '用户不存在'
    return render(request, 'login.html', {'error_msg': error_msg})


def logout(request):
    request.session.flush()
    return redirect('/login/')


def basicInfo(request):
    return render(request, 'admin_basicInfo.html')


def user_search(request):
    userlist = []
    # 啥都没输入 不跳转
    return render(request, 'admin_userManagement/admin_userManagement_student.html')


def login_submit(request):
    error_msg = ''
    if request.method == 'POST':
        sid = request.POST.get('sid', None)
        pwd = request.POST.get('password', None)
        try:
            user = models.User.objects.filter(sid=sid)
            if user.password == pwd:
                if user.state == 1:
                    return redirect('/teareserve/')
                elif user.state == 2:
                    return redirect('/stureserve/')
                elif user.state == 3:
                    return redirect('/admin_userManagement/')
                elif user.state == 4:
                    return redirect('/admin_userManagement/')
            else:
                error_msg = '密码错误'
        except:
            error_msg = '用户不存在'
            return render(request, 'login.html', {'error_msg': error_msg})


class registerView(View):
    def get(self, request):
        select_class = SelectClassForm()
        select_usertype = SelectUsertypeForm()
        select_college = SelectCollegeForm()
        return render(request, 'register.html', {'select_class': select_class, 'select_usertype': select_usertype,
                                             'select_college': select_college})

    def post(self, request):
        username = request.POST.get('username', '')
        pwd = request.POST.get('password')
        usertype = request.POST.get('usertype', 0)
        collegeId = request.POST.get('collegeId', 0)
        classId = request.POST.get('classId', 0)

        if usertype == 4:
            collegeId = 0
            classId = 0
        elif usertype == 3 or usertype == 2:
            classId = 0

        max_uid_dict = models.User.objects.all().aggregate(max=Max('uid'))
        sid = '4192' + str(max_uid_dict['max'] + 1)

        models.User.objects.create(state=usertype,
                                   name=username,
                                   sid=sid,
                                   password=pwd,
                                   college=collegeId,
                                   class_field=classId)

        return render(request, 'register_success.html', {'sid': sid, 'username': username})


def user_center(request):
    return render(request, 'user_center/user_center.html')


def pwd_change(request):
    return render(request, 'user_center/pwd_change.html')


def ajax(request):
    if request.method == 'POST':  # if request.is_ajax(): 判断是不是ajax请求
        n1 = request.POST.get('num1')
        n2 = request.POST.get('num2')
        n3 = int(n1) + int(n2)
        print(n3)
        return HttpResponse('yes')
    return render(request, 'tests/ajax.html')
